package me.helllp.bootman.back.logic.system.services.impl;

import java.util.UUID;

import org.apache.tomcat.util.buf.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import me.helllp.bootman.back.BackConst;
import me.helllp.bootman.back.config.BackErrorCodeEnum;
import me.helllp.bootman.back.logic.system.services.UserService;
import me.helllp.bootman.back.logic.system.vo.User001Input;
import me.helllp.bootman.back.mapper.SusrUserMapper;
import me.helllp.bootman.back.model.SusrUser;
import me.helllp.bootman.back.services.TokenService;
import me.helllp.bootman.back.utils.LocalSessionFactory;
import me.helllp.bootman.common.base.BaseReturn;
import me.helllp.bootman.common.services.LoginUserServices;
import me.helllp.bootman.common.services.RedisTemplateService;
import me.helllp.bootman.common.utils.ResultUtil;

@Service
public class UserServiceImpl implements UserService{
	@Autowired
	private LoginUserServices<?> loginService;

	@Autowired
	private TokenService tokenService;
	
	@Autowired
	private SusrUserMapper userMapper;
	
	@Autowired
	private RedisTemplateService redisService;
	
	@Override
	public BaseReturn logicUser001(User001Input input) {
		if(loginService.login(input.getPrincipals(),input.getCredentials())){
			SusrUser userBean = userMapper.getUserByPhone(input.getPrincipals());
			
			//	角色和权限的获取
			String roles = StringUtils.join(loginService.findRoles(userBean.getId()).toArray(new String[0]));
			String perms = StringUtils.join(loginService.findPermissions(userBean.getId()).toArray(new String[0]));
			
			String uuid = UUID.randomUUID().toString();
			//	登录通过
			String token = tokenService.signToken(uuid, userBean.getId(), BackConst.TOKEN_SIGNER, BackConst.TOKEN_DEFAULT_PERIOD, roles, perms);
			
			//	需要进行缓存
			redisService.set(userBean.getId() + "",token,BackConst.TOKEN_DEFAULT_PERIOD);
			LocalSessionFactory.setUserId(userBean.getId());
			
			return ResultUtil.genSuccessResult(token);
		}
		
		return BackErrorCodeEnum.SYS_LOGIN_01.getResult();
	}

	@Override
	public BaseReturn logicUser002() {
		Long userId = LocalSessionFactory.getUserId();
		
		redisService.remove(userId + "");
		
		return ResultUtil.genSuccessResult(null);
	}
}
